import AppleStore from "./AppleStore";
import { makeObservable, observable, computed, action, flow } from "mobx";

export default class AppleBasketStore {
  constructor() {
    this.basket = [new AppleStore(1), new AppleStore(2), new AppleStore(3)]
    this.isPicking = false
    makeObservable(this, {
      basket: observable,
      isPicking: observable,
      existApples: computed,
      currentApples: computed,
      eatedApples: computed,
      pickText: computed,
      pickApple: flow.bound
    })
  }
  * pickApple() {
    this.isPicking = true
    setTimeout(yield () => {
      this.addApple()
      this.isPicking = false
    }, 1000);
  }

  addApple() {
    if (!this.basket.length) {
      this.basket.push(new AppleStore(1))
    } else {
      this.basket.push(new AppleStore(this.basket.length + 1))
    }
  }
  get existApples() {
    return this.basket.filter(apple => !apple.isEated)
  }
  get currentApples() {
    return {
      number: this.existApples.length,
      weight: this.existApples.reduce((w, apple) => w += Number(apple.weight), 0).toFixed(0)
    }
  }
  get eatedApples() {
    const eateds = this.basket.filter(apple => apple.isEated)
    return {
      number: eateds.length,
      weight: eateds.reduce((w, apple) => w += Number(apple.weight), 0).toFixed(0)
    }
  }
  get pickText() {
    return this.isPicking ? '正在采摘...' : '摘苹果'
  }
}